// ==UserScript==
// @name         知乎快捷工具
// @namespace    https://gitee.com/liaoyinglong
// @version      0.1
// @description  一键收起文章
// @author       lyl
// @match        https://www.zhihu.com/*
// @grant        none
// @require      https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js
// ==/UserScript==

(function() {
  //#region 源码

  const setCollapsedButton = function() {
    const $CornerButtons = $('.CornerButtons');
    if (!$CornerButtons.length) return;

    const $CollapsedTogetherButton = $('.CollapsedTogetherButton');
    if ($CollapsedTogetherButton.length) return;

    const $button = $(`<button>收起</button>`)
      .addClass('Button CornerButton Button--plain CollapsedTogetherButton')
      .attr('data-tooltip', '一键收起全部')
      .attr('data-tooltip-position', 'left')
      .attr('data-tooltip-will-hide-on-click', 'true')
      .on('click', () => {
        $('.RichContent-collapsedText').each((_, btn) => btn.click());
      });

    const $div = $(`<div class='CornerAnimayedFlex'></div>`).append($button);

    $div.insertBefore($CornerButtons[0].children[0]);
  };
  const setCollapsedButtonInTopicPage = function() {
    if ($('.CollapsedButtonInTopicPage').length) return;
    const $button = $(
      `<div class="zh-backtotop CollapsedButtonInTopicPage">
          <div class="btn-backtotop btn-action" style="
          display: flex;
          justify-content: center;
          align-items: center">
            收起
          </div>
      </div>`
    ).css({
      opacity: 1,
      bottom: '165px'
    });

    $('body').append($button);
  };

  const bootstrap = function() {
    const url = window.location.href;
    const topicDetailReg = /(topic\/).*$/;
    const topicReg = /(topic#?).*$/;

    if (topicReg.test(url) && !topicDetailReg.test(url)) {
      setCollapsedButtonInTopicPage();
      return;
    }

    setCollapsedButton();
  };

  bootstrap();

  $(() => {
    bootstrap();
  });

  //#endregion 源码
})();
